<template>
	<div>
		<CustomDialog
			:title="state.dialog.title"
			v-model:visible="state.dialog.isShowDialog"
			dialogWidth="900px"
			@close="closeDialog"
			:dialogFooterBtn="true"
		>
			<!-- <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="1100px" @close="closeDialog"> -->
			<el-form ref="discountDialogFormRef" :model="state.ruleForm" size="default" label-width="90px">
				<el-form-item label="商品名称:" v-if="state.choiceGoods"> {{ state.item.title }}</el-form-item>

				<div class="activity-item" v-if="!state.choiceGoods">
					<el-form-item label="选择商品">
						<el-button type="primary" link @click="addItem"> 选择商品</el-button>
					</el-form-item>
				</div>

				<table class="qgg-table" v-if="state.choiceGoods">
					<thead>
						<tr>
							<th v-for="(header, index) in skuHeader" :key="index">{{ header }}</th>
							<th>零售价格(元)</th>
							<th>商品原价(元)</th>
							<th>库存(个)</th>
							<th>可兑换数量</th>
							<th>兑换积分</th>
							<th>兑换价格</th>
							<th>设置</th>
						</tr>
					</thead>
					<tbody>
						<tr></tr>
						<tr v-for="(item, index) in state.ruleForm.goodsSkus" :key="index">
							<td v-for="(v, index) in item.specification" :key="index">
								{{ v.value }}
							</td>
							<td>
								{{ item.price }}
							</td>
							<td>
								{{ item.originalPrice }}
							</td>
							<td>
								{{ item.stock }}
							</td>

							<td>
								<el-form-item
									size="small"
									label-width="0px"
									style="margin-bottom: 0px"
									:rules="{ required: true, message: '可兑换不能为空', trigger: 'blue' }"
									:prop="'goodsSkus.' + index + '.exchangeCount'"
								>
									<el-input-number
										v-model="item.exchangeCount"
										:min="0"
										controls-position="right"
										size="small"
										:disabled="item.enable == 0"
										clearable
									/>
								</el-form-item>
							</td>
							<td>
								<el-form-item
									label-width="0px"
									size="small"
									style="margin-bottom: 0px"
									:rules="{ required: true, message: '兑换不能为空', trigger: 'blue' }"
									:prop="'goodsSkus.' + index + '.exchangeScore'"
								>
									<el-input-number
										v-model="item.exchangeScore"
										:min="0"
										controls-position="right"
										size="small"
										:disabled="item.enable == 0"
										clearable
									/>
								</el-form-item>
							</td>
							<td>
								<el-form-item
									label-width="0px"
									size="small"
									style="margin-bottom: 0px"
									:rules="{ required: true, message: '兑换价格不能为空', trigger: 'blue' }"
									:prop="'goodsSkus.' + index + '.exchangePrice'"
								>
									<el-input-number
										v-model="item.exchangePrice"
										:min="0"
										:precision="2"
										step="0.1"
										controls-position="right"
										size="small"
										:disabled="item.enable == 0"
									/>
								</el-form-item>
							</td>
							<td>
								<el-button text type="primary" v-if="item.enable == 0" @click="item.enable = 1">参与</el-button>
								<el-button v-else text type="primary" @click="item.enable = 0">取消</el-button>
							</td>
						</tr>
					</tbody>
				</table>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(discountDialogFormRef)" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
			<!-- </el-dialog> -->
		</CustomDialog>
		<ItemDialog ref="ItemChoiceRef" @choice="choiceItem"></ItemDialog>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, defineAsyncComponent } from 'vue';
import { type FormInstance } from 'element-plus';
import msg from '/@/utils/messageUtils';
import { ScoreApi } from '/@/api/shop/score';
import { goodsApi } from '/@/api/goods/index';
import _ from 'lodash';

const ItemDialog = defineAsyncComponent(() => import('/@/views/goods/goods/choice/choice_index.vue'));
const ItemChoiceRef = ref();
const discountDialogFormRef = ref();
const emit = defineEmits(['refresh']);
const state = reactive({
	ruleForm: {
		id: '',
		goodsId: '',
		title: '',
		goodsPrice: '',
		exchangeCount: '',
		exchangeScore: '',
		exchangePrice: '',
		specs: [] as any[],
		goodsSkus: [] as any[],
	},
	choiceGoods: false,
	item: {} as any,
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});
const skuHeader = ref<string[]>([]);
const goodsSkus = ref<any[]>([]);

const onCancel = () => {
	closeDialog();
};

const resolveEditContentGoodsSpec = () => {
	resolveEditContent(state.item.itemProps);
	state.item.itemProps = state.ruleForm.goodsSkus;
};

const choiceItem = async (choiceGoodsItems: ChoiceGoodsItem[]) => {
	console.log('choiceGoodsItem: ', choiceGoodsItems);
	state.item = {
		goodsId: choiceGoodsItems[0].id,
		image: choiceGoodsItems[0].image,
		title: choiceGoodsItems[0].title,
		price: choiceGoodsItems[0].price,
		itemProps: [],
	};
	state.ruleForm.title = choiceGoodsItems[0].title;
	state.choiceGoods = true;
	if (_.isEmpty(state.item.itemProps)) {
		console.log('属性为空');
		const { data } = await goodsApi().view(state.item.goodsId);
		if (data.spec == 1) {
			resolveMangSpecContent(data.goodsAttrs, data.goodsSkus);
		} else {
			// 单规格
			resolveSingleSpecContent(data);
		}
		state.item.itemProps = state.ruleForm.goodsSkus;
	} else {
		console.log('属性有值');
		// 编辑修改
		resolveEditContent(state.item.itemProps);
		state.item.itemProps = state.ruleForm.goodsSkus;
	}
};

const addItem = async () => {
	//  TODO 查询已经设置的商品,不能重复选择....

	let { data } = await ScoreApi().joinGoods();
	console.log('data-join-goods:  ', data);
	ItemChoiceRef.value.openDialog(data);
};
// 关闭弹窗
const closeDialog = () => {
	console.log('关闭窗口');
	state.dialog.isShowDialog = false;
	clearArraysContent();
	state.choiceGoods = false;
};

const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid) => {
		if (valid) {
			try {
				console.log('state.item.itemProps: ', state.item.itemProps);
				if (state.dialog.type === 'add') {
					const { data } = await ScoreApi().create({
						goodsId: state.item.goodsId,
						scoreExchangeGoods: state.item.itemProps,
						title: state.item.title,
					});
					console.log('data: ', data);
				} else {
					await ScoreApi().update({
						id: state.ruleForm.id,
						goodsId: state.ruleForm.goodsId,
						scoreExchangeGoods: state.item.itemProps,
						title: state.item.title,
					});
				}
				msg().success('操作成功');
				closeDialog();
				emit('refresh');
			} catch (e) {
				console.log('e: ', e);
				msg().error('操作失败');
			}
		}
	});
};

const openDialog = async (type: string, id: string) => {
	if (type === 'edit') {
		state.dialog.title = '兑换规则';
		state.dialog.submitTxt = '修 改';
		state.dialog.type = 'edit';
		state.ruleForm.id = id;
		const { data } = await ScoreApi().view(id);
		state.ruleForm.goodsId = data.goodsId;
		state.ruleForm.title = data.title;
		state.ruleForm.id = id;
		state.item.itemProps = data.scoreExchangeGoodsVOS;
		state.choiceGoods = true;
		state.item.title = data.title;
		resolveEditContentGoodsSpec();
	} else {
		state.dialog.title = '兑换规则';
		state.dialog.submitTxt = '新 增';
		state.dialog.type = type;
	}
	state.dialog.isShowDialog = true;
};
const clearArraysContent = () => {
	state.item = {};
};

// 开始编辑多sku
const resolveEditContent = (props: any) => {
	console.log('props: ', props);
	clearSkuSpec();
	if (!_.isEmpty(props[0].specification)) {
		props[0].specification.forEach((e: any) => {
			skuHeader.value.push(e.key);
		});
	}
	props.forEach((e: any) => {
		let gs: any = {
			image: e.image,
			specification: [],
			price: e.price,
			originalPrice: e.originalPrice,
			stock: e.stock,
			sales: e.sales,
			exchangeCount: e.exchangeCount,
			exchangeScore: e.exchangeScore,
			exchangePrice: e.exchangePrice,
			enable: e.enable,
		};
		e.specification.forEach((element: any) => {
			gs.specification.push({
				key: element.key,
				value: element.value,
			});
		});
		goodsSkus.value.push(gs);
		state.ruleForm.goodsSkus.push(gs);
	});
};
const resolveSingleSpecContent = (e: any) => {
	clearSkuSpec();
	state.ruleForm.goodsSkus.push({
		image: e.image,
		specification: [],
		price: e.price,
		originalPrice: e.originalPrice,
		stock: e.stock,
		sales: e.sales,
		exchangeCount: 0,
		exchangeScore: 0,
		exchangePrice: 0,
		enable: 0,
	});
};
const resolveMangSpecContent = (goodsAttrs: any, goodsSkusParam: any) => {
	console.log('goodsAttrs: ', goodsAttrs);
	console.log('goodsSkusParam: ', goodsSkusParam);
	clearSkuSpec();
	goodsAttrs.forEach((e: any) => {
		let si: any = {
			key: Date.now(),
			value: e.attribute,
			specContents: [],
		};
		e.value.forEach((element: string) => {
			si.specContents.push({
				key: Date.now(),
				value: element,
			});
		});

		state.ruleForm.specs.push(si);
	});

	goodsSkusParam[0].specification.forEach((v: any) => {
		skuHeader.value.push(v.key);
	});

	goodsSkusParam.forEach((e: any) => {
		let gs: any = {
			image: e.image,
			specification: [],
			price: e.price,
			originalPrice: e.originalPrice,
			stock: e.stock,
			sales: e.sales,
			exchangeCount: 0,
			exchangeScore: 0,
			exchangePrice: 0,
			enable: 0,
		};
		e.specification.forEach((element: any) => {
			gs.specification.push({
				key: element.key,
				value: element.value,
			});
		});
		goodsSkus.value.push(gs);
		state.ruleForm.goodsSkus.push(gs);
	});
};

const clearSkuSpec = () => {
	console.log('清空数据....');
	goodsSkus.value = [];
	state.ruleForm.goodsSkus = [];
	skuHeader.value = [];
};

// 结束编辑多sku
defineExpose({ openDialog });
</script>

<style scoped>
.item-content {
	width: 400px;
}

.exec-width {
	width: 250px;
	margin-left: 10px;
}

.item-header {
	background-color: rgba(223, 230, 233, 1);
}

.item-body {
	margin-top: 10px;
}

.content {
	flex: 1;
}

.oper {
	width: 60px;
}

.goods-img {
	width: 50px;
	height: 50px;
}

.goods-content {
	margin-left: 10px;
	flex: 1;

	.goods-title {
		font-size: 14px;
		height: 20px;
		line-height: 20px;
		overflow: hidden;
		text-overflow: ellipsis;
		/* white-space: nowrap; */
		/* text-overflow: ellipsis; */
		display: -webkit-box;
		-webkit-line-clamp: 1;
		-webkit-box-orient: vertical;
		padding-right: 5px;
	}

	.goods-price {
		font-size: 12px;
		height: 20px;
		line-height: 40px;
		color: rgba(255, 118, 117, 1);
	}
}

.qgg-table {
	border-collapse: collapse;
	width: 100%;
	border: 1px solid #c6c6c6 !important;
	margin-bottom: 20px;
	border-spacing: 0;
	table-layout: fixed;
}

.qgg-table th {
	border-collapse: collapse;
	border-right: 1px solid #c6c6c6 !important;
	border-bottom: 1px solid #c6c6c6 !important;
	background-color: #ddeeff !important;
	padding: 5px 9px;
	font-size: 14px;
	font-weight: normal;
	text-align: center;
}

.qgg-table td {
	border-collapse: collapse;
	border-right: 1px solid #c6c6c6 !important;
	border-bottom: 1px solid #c6c6c6 !important;
	padding: 5px 9px;
	font-size: 12px;
	font-weight: normal;
	text-align: center;
	word-break: break-all;
}

.qgg-table tr:nth-child(odd) {
	background-color: #fff !important;
}

.qgg-table tr:nth-child(even) {
	background-color: #f8f8f8 !important;
}

.center {
	display: flex;
	justify-content: center;
}
</style>
